import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ytbusiness/page/select_role/check_role.dart';
import 'package:ytbusiness/utils/helper.dart';

import 'cook.dart';

///网络请求库
class Http {
  Dio dio;

  static const String TYPE_GET = "get";
  static const String TYPE_POST = "post";

  static Http get instance => _getInstance();
  static Http _instance;

  factory Http() => _getInstance();

  // 初始化
  Http._internal() {
    if (dio == null) {
      BaseOptions options = BaseOptions();
      dio = Dio(options);
    }
  }

  /// 单例
  static Http _getInstance() {
    if (_instance == null) {
      _instance = new Http._internal();
    }
    return _instance;
  }

  //get方法返回一个map的future类型
  Future get(
    String url, {
    Map<String, dynamic> data,
    BuildContext context,
  }) async {
    return _request(
      url,
      TYPE_GET,
      data: data,
      context: context,
    );
  }

  ///post方法
  Future post(
    String url, {
    Map<String, dynamic> data,
    BuildContext context,
  }) async {
    return _request(
      url,
      TYPE_POST,
      data: data,
    );
  }

  Future _request(
    String url,
    String type, {
    Map<String, dynamic> data,
    BuildContext context,
  }) async {
    print("url------>$url");
    try {
      dio.interceptors.add(CookieManager((await Cook.cookieJar)));
      Response response;
      Options options = Options(contentType: Headers.formUrlEncodedContentType);

      if (type == TYPE_GET) {
        response = await dio.get(url, queryParameters: data, options: options);
      } else if (type == TYPE_POST) {
        response = await dio.post(url, data: data, options: options);
      }
      print("data------>${response.data}");
      if (response.data["code"] == 4002) {
        await Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => CheckRole()),
            (route) => route == null);
        return;
      }

      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception("接口异常");
      }
    } catch (e) {
      print("--->$e");
    }
  }
}
